package service

import (
	"context"
	"github.com/go-kratos/kratos/v2/errors"
	"github.com/go-kratos/kratos/v2/log"
	"go.opentelemetry.io/otel"
	pb "helloworld/api/helloworld/v1"
	"helloworld/internal/biz"
)

// service层，处理简单业务逻辑。
// 处理Data Object对象

// 数据对象封装
func NewUserService(Data *biz.UserUsecase, logger log.Logger) *UserService {
	return &UserService{
		Data: Data,
		log:  log.NewHelper(logger),
	}
}

// 创建用户
func (s *UserService) CreateUser(ctx context.Context, req *pb.CreateUserRequest) (*pb.CreateUserReply, error) {
	s.log.Infof("input data %v", req)
	err := s.Data.Create(ctx, &biz.Data{
		Username: req.Username,
		Email:    req.Email,
		Password: req.Password,
	})
	if err != nil {
		return &pb.CreateUserReply{Data: 0}, errors.New(400, "BadUserArgument", "提供的用户参数无效")
	}
	return &pb.CreateUserReply{Data: 1}, err
}

// 更新用户信息
func (s *UserService) UpdateUser(ctx context.Context, req *pb.UpdateUserRequest) (*pb.UpdateUserReply, error) {
	s.log.Infof("input data %v", req)

	// email为唯一主键，先使用email进行查询用户是否存在
	eml := req.Email
	err := s.Data.CheckExist(ctx, eml)
	if err != nil {
		return nil, err
	}

	// 校验是否存在
	p, _ := s.Data.Get(ctx, req.Id)
	if p == nil {
		return nil, errors.NotFound("NotFound", "找不到资源。")
	}

	err = s.Data.Update(ctx, req.Id, &biz.Data{
		Username: req.Username,
		Email:    req.Email,
		Password: req.Password,
	})
	// 存在，进行更新
	if err != nil {
		return &pb.UpdateUserReply{
			Data: 0,
		}, errors.New(408, "RequestTimeout", "无法在允许的时间内完成该操作。")
	}
	// 返回response
	return &pb.UpdateUserReply{
		Data: 1,
	}, err
}

// 删除用户信息
func (s *UserService) DeleteUser(ctx context.Context, req *pb.DeleteUserRequest) (*pb.DeleteUserReply, error) {
	s.log.Infof("input data %v", req)

	// 校验是否存在
	p, _ := s.Data.Get(ctx, req.Id)
	if p == nil {
		return nil, errors.NotFound("NotFound", "找不到资源。")
	}

	// 存在，进行删除操作
	err := s.Data.Delete(ctx, req.Id)
	if err != nil {
		return &pb.DeleteUserReply{Data: 0}, err
	}
	return &pb.DeleteUserReply{Data: 1}, err
}

// 通过id获取用户信息
func (s *UserService) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.GetUserReply, error) {
	// 校验id是否为不合法id
	if req.Id < 1 {
		return nil, errors.New(409, "Overlimit", "请求资源超出系统限制。")
	}
	tr := otel.Tracer("api")
	ctx, span := tr.Start(ctx, "GetUser")
	defer span.End()
	// 获取
	p, err := s.Data.Get(ctx, req.Id)
	// 无用户对象
	if p == nil {
		return nil, errors.NotFound("NotFound", "找不到资源。")
	}
	if err != nil {
		return nil, err
	}
	return &pb.GetUserReply{Data: &pb.Data{Id: p.ID, Username: p.Username, Email: p.Email, Password: p.Password}}, nil
}

// 获取用户list
func (s *UserService) ListUser(ctx context.Context, req *pb.ListUserRequest) (*pb.ListUserReply, error) {
	ps, err := s.Data.List(ctx)
	reply := &pb.ListUserReply{}
	for _, p := range ps {
		reply.Data = append(reply.Data, &pb.Data{
			Id:       p.ID,
			Username: p.Username,
			Email:    p.Email,
			Password: p.Password,
		})
	}
	return reply, err
}
